import { forwardRef, useRef, useEffect } from "react"
import { mergedToString } from '../../utils';
const EditContent = (props, ref) => {
    const { children, className, style, setEditing, editableConfig } = props
    const inputRef = useRef(null)
    const value = mergedToString(children)
    useEffect(() => {
        onMounted()
    }, [])
    const onMounted = () => {
        const input = inputRef.current
        if (!input) return
        const { value } = input
        const { length } = value
        input.focus()
        // 设置光标位置在末尾
        input.setSelectionRange(length, length)
        // 动态计算样式
        const lineHeight = parseInt(window.getComputedStyle(input).lineHeight);
        const lines = value.split('\n').length;
        input.style.height = (lineHeight * lines + 12) + 'px';
        input.style.fontSize = style.fontSize
        input.style.fontWeight = style.fontWeight
    }
    const onBlur = () => {
        setEditing(false)
    }
    const onChange = (event) => {
        editableConfig.onChange && editableConfig.onChange(event.target.value)
    }
    return (
        <div ref={ref} className={`next-typography next-typography-edit-content ${className}`} style={style}>
            <textarea
                ref={inputRef}
                value={value}
                onBlur={onBlur}
                onChange={onChange}
                className="next-typography-edit-content-textarea"
            >
            </textarea>
        </div>
    )
}
export default forwardRef(EditContent)